from rest_framework import serializers
from .models import ExerciseSet, Exercise, UserExerciseRecord, UserExerciseSetProgress
from parser.serializers import ParsedQuestionSerializer

class ExerciseSerializer(serializers.ModelSerializer):
    """练习题序列化器"""
    source_question_data = ParsedQuestionSerializer(source='source_question', read_only=True)
    
    class Meta:
        model = Exercise
        fields = ['id', 'exercise_set', 'content', 'answer', 'explanation', 
                 'question_type', 'difficulty', 'created_at', 'updated_at', 
                 'source_question', 'source_question_data']
        read_only_fields = ['created_at', 'updated_at']

class ExerciseSetSerializer(serializers.ModelSerializer):
    """练习集序列化器"""
    questions_count = serializers.IntegerField(read_only=True)
    created_by_username = serializers.CharField(source='created_by.username', read_only=True)
    
    class Meta:
        model = ExerciseSet
        fields = ['id', 'title', 'description', 'created_by', 'created_by_username',
                 'created_at', 'updated_at', 'is_public', 'questions_count']
        read_only_fields = ['created_at', 'updated_at', 'questions_count']

class ExerciseSetDetailSerializer(ExerciseSetSerializer):
    """练习集详情序列化器，包含所有练习题"""
    questions = ExerciseSerializer(many=True, read_only=True)
    
    class Meta(ExerciseSetSerializer.Meta):
        fields = ExerciseSetSerializer.Meta.fields + ['questions']

class UserExerciseRecordSerializer(serializers.ModelSerializer):
    """用户练习记录序列化器"""
    exercise_data = ExerciseSerializer(source='exercise', read_only=True)
    username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = UserExerciseRecord
        fields = ['id', 'user', 'username', 'exercise', 'exercise_data', 
                 'user_answer', 'status', 'created_at', 'updated_at']
        read_only_fields = ['created_at', 'updated_at', 'username']

class UserExerciseSetProgressSerializer(serializers.ModelSerializer):
    """用户练习集进度序列化器"""
    exercise_set_data = ExerciseSetSerializer(source='exercise_set', read_only=True)
    username = serializers.CharField(source='user.username', read_only=True)
    progress_percentage = serializers.FloatField(read_only=True)
    
    class Meta:
        model = UserExerciseSetProgress
        fields = ['id', 'user', 'username', 'exercise_set', 'exercise_set_data',
                 'completed_count', 'correct_count', 'last_exercise', 
                 'started_at', 'last_activity_at', 'is_completed', 'progress_percentage']
        read_only_fields = ['started_at', 'last_activity_at', 'progress_percentage']

class ImportQuestionsSerializer(serializers.Serializer):
    """导入题目的序列化器"""
    document_id = serializers.IntegerField(required=True)
    title = serializers.CharField(required=True, max_length=200)
    description = serializers.CharField(required=False, allow_blank=True)
    is_public = serializers.BooleanField(default=False) 